package com.photoeditor.demo.ui.widget.image.edit;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.android.graffiti.ColorRadioButton;
import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.app.ItemClickSupport;
import com.photoeditor.demo.model.store.download.DownloadUtils;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.adapter.FontAdapter;
import com.photoeditor.demo.ui.widget.HRecyclerView;
import com.photoeditor.demo.ui.widget.MultiToggleImageButton;
import com.photoeditor.demo.ui.widget.image.compose.CustomizedEditText;
import com.photoeditor.demo.util.KeyBoardHelper;
import com.photoeditor.demo.util.font.FontHelper;

import java.util.List;


/**
 * 编辑界面编辑文字相关view和代码
 */
public class TextBarView extends RelativeLayout implements RadioGroup.OnCheckedChangeListener, ItemClickSupport.OnItemClickListener {

    /**
     * 图片编辑文字相关
     */
    private Context mContext;

    private WindowManager mWindowManager;

    private FrameLayout mShadeView;

    private ImageView mCancelView;

    private ImageView mConfirmView;

    public CustomizedEditText mEditText;

    private WindowManager.LayoutParams mLayoutParams;

    private HRecyclerView mFontListView;
    private FontAdapter mFontAdapter;
    private RadioGroup mColorsGroup;

    private MultiToggleImageButton mTextStyleBtn;

    private int mStyle = TEXT_STATE_0;
    public static final int TEXT_STATE_0 = 0;
    public static final int TEXT_STATE_1 = 1;
    public static final int TEXT_STATE_2 = 2;
    public static final int TEXT_STATE_3 = 3;

    private int mSelectColor = Color.WHITE;

    /**
     * 用于选择的COLOR
     */
    private final String COLORS[] = new String[]{
            "#bb0000",
            "#e93f2d",
            "#ff6e3f",
            "#ffb939",
            "#fdff2b",
            "#c4ff30",
            "#77e118",
            "#00b300",
            "#00d47f",
            "#00f3d4",
            "#00b2f4",
            "#0078f2",
            "#0035c3",
            "#00238c",
            "#4c4eff",
            "#965aff",
            "#d181ff",
            "#ff9eff",
            "#ff6c97",
            "#e73f57",
            "#60608c",
            "#000000",
            "#3c3c3c",
            "#999999",
            "#ffffff",
            "#feff9d"
    };


    public TextBarView(Context context) {
        this(context, null);
    }


    public TextBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    /**
     * 初始化后需要执行这个
     */
    public void init() {
        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
        setBackgroundResource(R.drawable.image_edit_sencond_bg);
        mColorsGroup = (RadioGroup) findViewById(R.id.graffito_popup_brushes_colors_gp);
        mFontListView = (HRecyclerView) findViewById(R.id.fontlistview);
//        int spacing = DeviceUtils.dip2px(getContext(), -8);
//        mFontListView.setSpacing(spacing);
        mFontAdapter = new FontAdapter();
        mFontAdapter.setData(FontHelper.getInstance().getFontList());
        mFontListView.setAdapter(mFontAdapter);
        ItemClickSupport itemClickSupport = new ItemClickSupport(mFontListView, mFontAdapter);
        itemClickSupport.setOnItemClickListener(this);
        mFontAdapter.setItemClickSupport(itemClickSupport);

        mColorsGroup.setOnCheckedChangeListener(this);
        mTextStyleBtn = (MultiToggleImageButton) findViewById(R.id.text_style);
        mTextStyleBtn.overrideImageIds(new int[]{
                R.drawable.ic_white_hold_review_normal,
                R.drawable.ic_white_hold_review_whitebg,
                R.drawable.ic_hold_review_graybg,
                R.drawable.ic_hold_review_black
        });
        mTextStyleBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mStyle++;
                mStyle = mStyle % 4;
                mTextStyleBtn.setState(mStyle);
                updateTextView(-1);
            }
        });
    }

    /**
     * 显示编辑框
     *
     * @param text
     */
    public void showEditText(String text) {
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        }
        if (mShadeView == null) {
            mShadeView = (FrameLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_picture_text_shade, null, false);
            mCancelView = (ImageView) mShadeView.findViewById(R.id.cancel);
            mConfirmView = (ImageView) mShadeView.findViewById(R.id.confirm);
            mEditText = (CustomizedEditText) mShadeView.findViewById(R.id.edit_text);
            mEditText.requestFocus();
            mEditText.setFocusable(true);
            mEditText.setFocusableInTouchMode(true);

            OnClickListener onclick = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.cancel) {
                        if (mShadeView.getParent() != null) {
                            KeyBoardHelper.hideKeyBoard(ComponentContext.getContext(), mEditText);
                            removeDialog();
                        }
                    } else if (v.getId() == R.id.confirm) {
                        if (mTextBarListener != null) {
                            mTextBarListener.onTextConfirmed(mEditText.getText().toString());
                        }
                        KeyBoardHelper.hideKeyBoard(ComponentContext.getContext(), mEditText);
                        if (mShadeView.getParent() != null) {
                            removeDialog();
                        }
                    } else {
                        if (mShadeView.getParent() != null) {
                            KeyBoardHelper.hideKeyBoard(ComponentContext.getContext(), mEditText);
                            removeDialog();
                        }
                    }
                }
            };
            mCancelView.setOnClickListener(onclick);
            mConfirmView.setOnClickListener(onclick);
            mShadeView.setOnClickListener(onclick);
        }

        if (mLayoutParams == null) {
            mLayoutParams = new WindowManager.LayoutParams();
            /**
             * 注意 设置成这样才能使用EditText的黏贴
             */
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;
            //设置图片格式，效果为背景透明
            mLayoutParams.format = PixelFormat.RGBA_8888;
            //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
            mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
            //调整悬浮窗显示的停靠位置为左侧置顶
            mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
            // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
            mLayoutParams.width = LayoutParams.MATCH_PARENT;
            mLayoutParams.height = LayoutParams.MATCH_PARENT;

            mLayoutParams.alpha = 1.0f;
            mLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
            //另一种方式 也可以
        }
        if (text == null) {
            text = "";
        }
        mEditText.setText(text);
        mEditText.setSelection(text.length());
        if (mShadeView.getParent() == null) {
            mWindowManager.addView(mShadeView, mLayoutParams);
        }
        KeyBoardHelper.showKeyBoardWithoutDelay(ComponentContext.getContext(), mEditText);
    }

    private void removeDialog() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    mWindowManager.removeView(mShadeView);
                } catch (Exception e) {
                }
            }
        }, 200);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId > 0) {
            ColorRadioButton button =
                    (ColorRadioButton) group.findViewById(checkedId);
            mSelectColor = button.getColor();
            updateTextView(checkedId);
        }
    }

    private void updateTextView(int checkedId) {
        int textColor = 0;
        int bgColor = 0;
        switch (mStyle) {
            case TEXT_STATE_0:
                textColor = mSelectColor;
                bgColor = Color.TRANSPARENT;
                break;
            case TEXT_STATE_1:
                if (mSelectColor == Color.WHITE) {
                    textColor = Color.BLACK;
                    bgColor = mSelectColor;
                } else {
                    textColor = Color.WHITE;
                    bgColor = mSelectColor;
                }
                break;
            case TEXT_STATE_2:
                textColor = mSelectColor;
                bgColor = ComponentContext.getContext().getResources().getColor(R.color.text_bg_color_gray);
                break;
            case TEXT_STATE_3:
                textColor = mSelectColor;
                bgColor = ComponentContext.getContext().getResources().getColor(R.color.text_bg_color_black);
                break;
        }
        if (mTextBarListener != null) {
            mTextBarListener.updateColor(textColor, bgColor, checkedId, mStyle);
        }
    }

    private TextBarListener mTextBarListener;

    public void setTextBarListener(TextBarListener textBarListener) {
        mTextBarListener = textBarListener;
    }

    public void setVisibility(int visibility, boolean checkBlack) {
        super.setVisibility(visibility);
        if (visibility == VISIBLE && checkBlack) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mColorsGroup != null) {
                        mColorsGroup.check(mColorsGroup.getChildAt(1).getId());
                    }
                }
            }, 250);
        }
    }

    public void reset(boolean checkBlack) {
        mStyle = TEXT_STATE_0;
        if (mTextStyleBtn != null) {
            mTextStyleBtn.setState(mStyle);
        }
        if (mColorsGroup != null) {
            if (checkBlack) {
                mColorsGroup.check(mColorsGroup.getChildAt(1).getId());
            } else {
                mColorsGroup.check(mColorsGroup.getChildAt(0).getId());
            }
        }
        findViewById(R.id.graffito_popup_brushes_colors).setScrollX(0);
        mFontListView.setSelectionNoAni(0);
        mFontAdapter.setSelIndex(0, null);
    }

    public void reset() {
        mStyle = TEXT_STATE_0;
        if (mTextStyleBtn != null) {
            mTextStyleBtn.setState(mStyle);
        }
        if (mColorsGroup != null) {
            mColorsGroup.check(mColorsGroup.getChildAt(0).getId());
        }
        findViewById(R.id.graffito_popup_brushes_colors).setScrollX(0);
        mFontListView.setSelectionNoAni(0);
        mFontAdapter.setSelIndex(0, null);
    }

    public void setParams(int checkId, int style, String fontKey) {
        mStyle = style;
        if (mTextStyleBtn != null) {
            mTextStyleBtn.setState(mStyle);
        }
        if (checkId > 0) {
            mColorsGroup.check(checkId);
        }
        if (checkId > 0 && checkId - 1 < mColorsGroup.getChildCount()) {
            View child = mColorsGroup.getChildAt(checkId - 1);
            findViewById(R.id.graffito_popup_brushes_colors).setScrollX(child.getLeft() - DeviceUtils.dip2px(getContext(), 8));
        }
        if (!TextUtils.isEmpty(fontKey)) {
            List<StoreOnlineBean> data = mFontAdapter.getData();
            int selPos = 0;
            for (int i = 0; i < data.size(); ++i) {
                StoreOnlineBean item = data.get(i);
                if (fontKey.equals(item.getPkgName())) {
                    selPos = i;
                    break;
                }
            }
            mFontListView.setSelectionNoAni(selPos);
            mFontAdapter.setSelIndex(selPos, null);
        }
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
        StoreOnlineBean bean = mFontAdapter.getData().get(position);
        if (bean == null) {
            return;
        }
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_FONT_BAR_CLICK,
                StatisticsConstant.UMENG_CUSTOM_EVENT_KEY_CLICK, bean.getPkgName());
        if (FontHelper.hasDownload(bean)) {
            Typeface typeface = FontHelper.loadFont(bean);
            if (mTextBarListener != null) {
                mTextBarListener.updateFont(typeface, bean.getPkgName());
            }
            mFontAdapter.setSelIndex(position, view);
        } else {
            if (!isResDownloading(bean)) {
                DownloadUtils.getInstance().startDownload(bean, BaseOnlineManager.NORMAL_RESOURCE_FILE);
                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_FONT_BAR_DOWNLOAD,
                        StatisticsConstant.UMENG_CUSTOM_EVENT_KEY_CLICK, bean.getPkgName());
            }
        }
    }

    public static boolean isResDownloading(StoreOnlineBean bean) {
        boolean isDownloading = false;
        switch (DownloadUtils.getInstance().getDownloadStatus(bean.getPkgName())) {
            case DownloadUtils.DOWNLOAD_DEFAULT:
            case DownloadUtils.DOWNLOAD_END:
                isDownloading = false;
                break;
            case DownloadUtils.DOWNLOAD_CLICK:
            case DownloadUtils.DOWNLOAD_BING:
                isDownloading = true;
                break;
        }
        return isDownloading;
    }

    public interface TextBarListener {

        void onTextConfirmed(String text);

        void updateColor(int textColor, int bgColor, int checkId, int style);

        void updateFont(Typeface typeface, String fontKey);
    }
}
